<template>
  <!--    修改或者添加spu-->
  <div>
    <el-form ref="addOrUpdateSpuForm" :model="spuInfo" label-width="80px">
      <!--        spu名称输入框-->
      <el-form-item label="spu名称">
        <el-input v-model="spuInfo.spuName"></el-input>
      </el-form-item>
      <!--        品牌选择框-->
      <el-form-item label="品牌">
        <el-select v-model="spuInfo.tmId" placeholder="请选择">
          <el-option
            v-for="spuBrand in spuBrandList" :key="spuBrand.id" :label="spuBrand.tmName" :value="spuBrand.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!--        spu描述-->
      <el-form-item label="spu描述">
        <el-input :rows="5" placeholder="SPU描述" type="textarea" v-model="spuInfo.description"></el-input>
      </el-form-item>
      <!--        spu图片上传墙-->
      <el-form-item label="spu图片">
        <el-upload
          action="dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <!--        销售属性选择-->
      <el-form-item label="销售属性">
        <el-select clearable v-model="temporaryBaseAttr" :placeholder="unSelectBaseAttr.length===0?'没有啦！！！' : `还有${unSelectBaseAttr.length}未选择`">
          <el-option
            v-for="unSelect in unSelectBaseAttr"
            :key="unSelect.id"
            :label="unSelect.name"
            :value="`${unSelect.id}______${unSelect.name}`">
          </el-option>
        </el-select>
<!--        添加销售属性按钮-->
        <el-button
          icon="el-icon-plus"
          style="margin-left: 10px" type="primary"
          :disabled="temporaryBaseAttr === ''"
          @click="addSaleAttr"
        >添加属性</el-button>
      </el-form-item>
      <!--      属性值表格-->
      <el-form-item>
        <el-table border :data="spuInfo.spuSaleAttrList">
          <el-table-column align="center" label="序号" type="index" width="70"></el-table-column>
          <el-table-column label="属性名" width="220" prop="saleAttrName"></el-table-column>
          <el-table-column label="属性值名称列表" prop="spuSaleAttrValueList">
            <!--              动态添加和删除tag-->
            <template slot-scope="{row,$index}">
              <el-tag
                style="margin-right: 5px"
                :key="tag.id"
                v-for="tag in row.spuSaleAttrValueList"
                type="success"
                closable
                :disable-transitions="false"
                @close="handleClose(row,tag)">
                {{tag.saleAttrValueName}}
              </el-tag>
              <el-input
                ref="attrValRef"
                style="width: 30%"
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model.trim="row.inputValue"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>

            </template>
          </el-table-column>
          <!--          操作属性-->
          <el-table-column label="操作" width="150" prop="date">
            <template slot-scope="{row,$index}">
              <el-button type="danger" icon="el-icon-delete" @click="deleteAttr($index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!--        确认或取消修改添加按钮-->
      <el-form-item>
        <el-button style="margin-right: 20px" type="primary" @click="editSpu">确认</el-button>
        <el-button type="info" @click="closeEdit">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import debounce from 'lodash.debounce'

export default {
  name: "AddOrUpdateSpu",
  data(){
    return {
      dialogImageUrl: '', // 图片大图展示路径
      dialogVisible: false, // 图片大图展示框
      // 品牌信息
      spuBrandList:[],
      // 基础的销售属性
      baseSaleAttrList:[],
      // spu图片的列表
      spuImageList:[],
      // 存放临时选择的基础属性值
      temporaryBaseAttr:'',
      spuInfo: {
        "category3Id": 0, // 三级分类Id
        "description": "", // spu描述
        "spuName": "", // spu名称
        "tmId": null, // 品牌Id
        "spuImageList": [  // spu图片列表
          // {
          //   "id": 0,
          //   "imgName": "string",
          //   "imgUrl": "string",
          // }
        ],
        "spuSaleAttrList": [ // 属性列表
          // {
          //   "baseSaleAttrId": 0,
          //   "saleAttrName": "",
          //   "spuSaleAttrValueList": [  // 属性值列表
          //     {
          //       "baseSaleAttrId": 0,
          //       "saleAttrName": "",
          //       "saleAttrValueName": "",
          //     }
          //   ]
          // }
        ]
      },
    }
  },
  methods: {
    // 获取修改spu初始化数据
    async initUpdateSpuInfo({id,category3Id}) {
      // spu基本信息
      let supBaseInfoRes = await this.$API.spu.apiGetSpuById(id)
      if (supBaseInfoRes.code === 200) {
        this.spuInfo = supBaseInfoRes.data
      }
      // 可选品牌列表
      let brandRes = await this.$API.spu.apiFindBrandList(category3Id)
      if (brandRes.code === 200) {
        this.spuBrandList = brandRes.data
      }
      // 获取基础的销售属性
      let attrRes = await this.$API.spu.apiGetSaleAttr()
      if(attrRes.code === 200) {
        this.baseSaleAttrList = attrRes.data
      }
      // 获取spu图片信息
      let imgRes = await this.$API.spu.apiGetSpuImgList(this.spuInfo.id)
      if(imgRes.code === 200) {
        // 对返回的图片数据做处理，name，url属性，让其展示在照片墙上面
        imgRes.data.forEach(item=>{
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.spuImageList = imgRes.data
      }
    },
    // 获取添加spu初始化的数据
    async initAddSpuInfo({category3Id}) {
      this.spuInfo.category3Id = category3Id
      // 可选品牌列表
      let brandRes = await this.$API.spu.apiFindBrandList(category3Id)
      if (brandRes.code === 200) {
        this.spuBrandList = brandRes.data
      }
      // 获取基础的销售属性
      let attrRes = await this.$API.spu.apiGetSaleAttr()
      if(attrRes.code === 200) {
        this.baseSaleAttrList = attrRes.data
      }
    },
    /* 删除图片
     *图片删除和添加需要重新收集图片列表信息
     *图片信息将来合并到spuInfo时需要把name,url去掉
     */
    handleRemove(file, fileList) {
      this.spuImageList = fileList
    },
    // 预览大图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片上传成功的回调
    handleSuccess(res, file) {
      // 存储新添加的图片的信息
      let newPicInfo = {
        name: file.name,
        url: res.data,
        imgName: file.name,
        imgUrl: res.data,
        spuId: this.spuInfo.id,
        uid: file.uid,
        status: file.status
      }
      this.spuImageList.push(newPicInfo)
    },
    // 添加销售属性
    addSaleAttr() {
      // 将收集到的字符串形式的name 和 id 转换为数组
      let arr = this.temporaryBaseAttr.split('______')
      // push到数组中
      this.spuInfo.spuSaleAttrList.push({baseSaleAttrId: parseInt(arr[0]),saleAttrName: arr[1],spuSaleAttrValueList: []})
      this.temporaryBaseAttr = ''
    },
    // 删除销售属性
    deleteAttr(index){
      this.spuInfo.spuSaleAttrList.splice(index,1)
    },
    // 删除tag的回调
    handleClose(row,tag) {
      let deleteIndex // 当前tag在当前行的索引
      row.spuSaleAttrValueList.forEach((item,index)=>{
        if (item.id === tag.id) {
          deleteIndex = index
        }
      })
      row.spuSaleAttrValueList.splice(deleteIndex,1)
    },
    // tag进行添加的回调
    handleInputConfirm: debounce(function(row){
      // 遍历已有的属性值，检查是否重名
      let checked = row.spuSaleAttrValueList.every(item=>{
        return item.saleAttrValueName !== row.inputValue
      })
      if(!checked) {
        this.$message.error('属性值不可以重复')
      }else if(row.inputValue === ''){
        this.$message.info('属性值不可以为空哦！')
      }else {
        row.spuSaleAttrValueList.push( {baseSaleAttrId: row.baseSaleAttrId, saleAttrName: row.saleAttrName, saleAttrValueName: row.inputValue})
      }
      row.inputValue = ''
      row.inputVisible = false
      delete row.inputValue
      delete row.inputVisible
    },1000,{leading: true, trailing: false}),
    // 点击展示添加tag的input框回调
    showInput(row) {
      // 往row添加控制input显示隐藏，输入数据的字段
      this.$set(row,'inputVisible', true)
      this.$set(row,'inputValue','')
      this.$nextTick(()=>{
        this.$refs.attrValRef.focus()
      })
    },
    // 重置整个表单的信息
    resetForm(){
      // this._data 当前data里面的数据
      // this.$options.data() 当前组件最初的数据
      // Object.assign( target , source )
      Object.assign(this._data, this.$options.data())
    },
    // 取消添加或者修改spu
    closeEdit() {
      // 重置表单
      this.resetForm()
      // 跳转回展示页
      this.$emit('changeShow','show')
      this.$message.info('已取消')
    },
    // 最终确认或者修改Spu
    async editSpu() {
      // 先处理图片数据
      this.spuInfo.spuImageList = []
      this.spuImageList.forEach(item=>{
        this.spuInfo.spuImageList.push({
          id: item.id,
          imgUrl: item.imgUrl,
          imgName: item.imgName,
          spuId: item.spuId
        })
      })
      // 如果没有id是添加spu，如果有id是修改spu
      if(this.spuInfo.id) {
        console.log('更新')
        let res = await this.$API.spu.apiUpdateSpuInfo(this.spuInfo)
        if(res.code !== 200) {
          this.$message.error('编辑失败')
        }else {
          this.resetForm()
          this.$emit('changeShow','show','update')
          this.$message.success('编辑成功')}
        }else {
          let res = await this.$API.spu.apiSaveSpuInfo(this.spuInfo)
        if(res.code !== 200) {
          this.$message.error('添加失败')
        }else {
          this.resetForm()
          this.$emit('changeShow','show','add')
          this.$message.success('添加成功')}
        }
      }
  },
  computed:{
    // 未被选择的基础属性
    unSelectBaseAttr() {
      return this.baseSaleAttrList.filter(baseItem=>{
        let flag = this.spuInfo.spuSaleAttrList.every(item=>{
          return item.baseSaleAttrId !== baseItem.id
        })
        return flag === true
      })
    }
  }
}
</script>

<style scoped>

</style>
